class NovelToComicApp {
    constructor() {
        console.log('初始化小说转漫画应用...');
        
        // 获取DOM元素
        this.novelText = document.getElementById('novel-text');
        this.generateBtn = document.getElementById('generate-btn');
        this.progressSection = document.getElementById('progress-section');
        this.resultSection = document.getElementById('result-section');
        
        // 检查元素是否存在
        if (!this.novelText || !this.generateBtn) {
            console.error('关键DOM元素未找到！');
            return;
        }
        
        // 使用后端服务的URL
        this.API_BASE_URL = 'http://localhost:5000';
        this.comicRenderer = new ComicRenderer('comic-viewer', this.API_BASE_URL);
        this.currentStyle = 'manga';
        
        this.initEventListeners();
        this.updateGenerateButton();
        
        console.log('应用初始化完成');
    }
    
    initEventListeners() {
        console.log('初始化事件监听器...');
        
        // 文本输入监听
        this.novelText.addEventListener('input', () => {
            console.log('文本输入变化');
            this.updateWordCount();
            this.updateGenerateButton();
        });
        
        // 标签页切换
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                console.log('切换标签:', e.target.dataset.tab);
                this.switchTab(e.target.dataset.tab);
            });
        });
        
        // 风格选择
        document.querySelectorAll('input[name="comic-style"]').forEach(radio => {
            radio.addEventListener('change', (e) => {
                console.log('选择风格:', e.target.value);
                this.currentStyle = e.target.value;
            });
        });
        
        // 生成按钮 - 修复事件绑定
        this.generateBtn.addEventListener('click', (e) => {
            console.log('生成按钮被点击');
            e.preventDefault();
            this.generateComic();
        });
        
        // 重新生成按钮
        const regenerateBtn = document.getElementById('regenerate');
        if (regenerateBtn) {
            regenerateBtn.addEventListener('click', (e) => {
                console.log('重新生成按钮被点击');
                e.preventDefault();
                this.generateComic();
            });
        }
        
        // 下载全部按钮
        const downloadAllBtn = document.getElementById('download-all');
        if (downloadAllBtn) {
            downloadAllBtn.addEventListener('click', (e) => {
                console.log('下载全部按钮被点击');
                e.preventDefault();
                this.comicRenderer.downloadAllPages();
            });
        }
        
        console.log('事件监听器初始化完成');
    }
    
    switchTab(tabName) {
        console.log('切换到标签:', tabName);
        
        // 更新标签按钮状态
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.tab === tabName);
        });
        
        // 更新标签内容
        document.querySelectorAll('.tab-pane').forEach(pane => {
            pane.classList.toggle('active', pane.id === `${tabName}-tab`);
        });
    }
    
    updateWordCount() {
        const text = this.novelText.value;
        const wordCount = text.length;
        const sceneEstimate = Math.ceil(wordCount / 200);
        
        const wordCountElement = document.getElementById('word-count');
        const sceneEstimateElement = document.getElementById('scene-estimate');
        
        if (wordCountElement) wordCountElement.textContent = wordCount;
        if (sceneEstimateElement) sceneEstimateElement.textContent = sceneEstimate;
    }
    
    updateGenerateButton() {
        const hasText = this.novelText.value.trim().length > 0;
        this.generateBtn.disabled = !hasText;
        
        // 更新按钮文本
        const btnText = this.generateBtn.querySelector('.btn-text');
        if (btnText) {
            btnText.textContent = hasText ? '开始生成漫画' : '请输入小说文本';
        }
    }
    
    async generateComic() {
        console.log('开始生成漫画流程...');
        
        const novelText = this.novelText.value.trim();
        
        if (!novelText) {
            alert('请输入小说文本');
            return;
        }
        
        if (novelText.length < 50) {
            alert('文本太短，请至少输入50个字符');
            return;
        }
        
        if (novelText.length > 10000) {
            alert('文本过长，请控制在10000字符以内');
            return;
        }
        
        try {
            this.showProgressSection();
            this.updateProgress(0, '准备生成...');
            
            // 第一步：处理小说文本
            this.updateStepStatus('step-analyze', 'processing');
            console.log('开始处理小说文本...');
            const scenes = await this.processNovel(novelText);
            console.log('小说处理完成，场景数:', scenes.length);
            this.updateProgress(25, '文本分析完成');
            this.updateStepStatus('step-analyze', 'completed');
            
            // 第二步：生成场景描述
            this.updateStepStatus('step-scenes', 'processing');
            await this.delay(1000);
            this.updateProgress(50, '场景分析完成');
            this.updateStepStatus('step-scenes', 'completed');
            
            // 第三步：生成漫画图像
            this.updateStepStatus('step-images', 'processing');
            console.log('开始生成漫画图像...');
            const comicPages = await this.generateComicPages(scenes, this.currentStyle);
            console.log('漫画生成完成，页面数:', comicPages.length);
            this.updateProgress(75, '图像生成完成');
            this.updateStepStatus('step-images', 'completed');
            
            // 第四步：组合页面
            this.updateStepStatus('step-combine', 'processing');
            await this.delay(500);
            this.updateProgress(100, '漫画生成完成');
            this.updateStepStatus('step-combine', 'completed');
            
            // 显示结果
            this.showResultSection(comicPages);
            
        } catch (error) {
            console.error('生成漫画错误:', error);
            this.showError('生成失败: ' + error.message);
        }
    }
    
    async processNovel(text) {
        console.log('发送文本处理请求...', text.substring(0, 100) + '...');
        
        const response = await fetch(`${this.API_BASE_URL}/api/process-novel`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ text: text })
        });
        
        if (!response.ok) {
            const errorText = await response.text();
            console.error('API响应错误:', response.status, errorText);
            throw new Error(errorText || `文本处理失败 (${response.status})`);
        }
        
        const data = await response.json();
        console.log('文本处理成功:', data);
        return data.scenes;
    }
    
    async generateComicPages(scenes, style) {
    console.log('发送漫画生成请求...', { scenes: scenes.length, style });
    
    try {
        const response = await fetch(`${this.API_BASE_URL}/api/generate-comic`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ 
                scenes: scenes,
                style: style
            })
        });
        
        if (!response.ok) {
            const errorText = await response.text();
            console.error('API响应错误:', response.status, errorText);
            throw new Error(errorText || `漫画生成失败 (${response.status})`);
        }
        
        const data = await response.json();
        console.log('漫画生成成功:', data);
        
        // 验证数据
        if (!data.pages || data.pages.length === 0) {
            throw new Error('服务器返回了空页面数据');
        }
        
        // 验证每个页面都有page_id
        for (const page of data.pages) {
            if (!page.page_id) {
                console.warn('页面缺少page_id:', page);
            }
        }
        
        return data.pages;
        
    } catch (error) {
        console.error('生成漫画页面时出错:', error);
        throw error;
    }
}
    
    showProgressSection() {
        this.progressSection.style.display = 'block';
        this.resultSection.style.display = 'none';
        this.generateBtn.disabled = true;
        
        // 更新按钮状态
        const btnText = this.generateBtn.querySelector('.btn-text');
        const spinner = this.generateBtn.querySelector('.loading-spinner');
        
        if (btnText) btnText.textContent = '生成中...';
        if (spinner) spinner.style.display = 'block';
        
        // 重置进度
        this.updateProgress(0, '准备中...');
        this.resetStepStatuses();
    }
    
    updateProgress(percent, text) {
        const progressFill = document.getElementById('progress-fill');
        const progressText = document.getElementById('progress-text');
        const progressPercent = document.getElementById('progress-percent');
        
        if (progressFill) progressFill.style.width = percent + '%';
        if (progressText) progressText.textContent = text;
        if (progressPercent) progressPercent.textContent = percent + '%';
    }
    
    resetStepStatuses() {
        const steps = ['analyze', 'scenes', 'images', 'combine'];
        steps.forEach(step => {
            const element = document.getElementById(`step-${step}`);
            if (element) {
                element.textContent = '等待';
                element.className = 'step-status';
                element.parentElement.className = 'progress-step';
            }
        });
    }
    
    updateStepStatus(stepId, status) {
        const element = document.getElementById(stepId);
        if (!element) return;
        
        const parent = element.parentElement;
        
        element.textContent = status === 'processing' ? '处理中' : 
                            status === 'completed' ? '完成' : '等待';
        element.className = `step-status ${status}`;
        parent.className = `progress-step ${status}`;
    }
    
    showResultSection(pages) {
        this.progressSection.style.display = 'none';
        this.resultSection.style.display = 'block';
        this.generateBtn.disabled = false;
        
        // 恢复按钮状态
        const btnText = this.generateBtn.querySelector('.btn-text');
        const spinner = this.generateBtn.querySelector('.loading-spinner');
        
        if (btnText) btnText.textContent = '开始生成漫画';
        if (spinner) spinner.style.display = 'none';
        
        this.comicRenderer.renderComic(pages);
        
        // 滚动到结果区域
        this.resultSection.scrollIntoView({ behavior: 'smooth' });
    }
    
    showError(message) {
        alert(message);
        this.progressSection.style.display = 'none';
        this.generateBtn.disabled = false;
        
        // 恢复按钮状态
        const btnText = this.generateBtn.querySelector('.btn-text');
        const spinner = this.generateBtn.querySelector('.loading-spinner');
        
        if (btnText) btnText.textContent = '开始生成漫画';
        if (spinner) spinner.style.display = 'none';
    }
    
    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

// 初始化应用 - 确保DOM完全加载
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM加载完成，初始化应用...');
    try {
        window.app = new NovelToComicApp();
        console.log('应用初始化成功');
    } catch (error) {
        console.error('应用初始化失败:', error);
    }
});

// 如果脚本加载失败，显示错误信息
window.addEventListener('error', (e) => {
    console.error('全局错误:', e.error);
});